package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.PaymentTaskDao;
import com.xbongbong.saas.domain.entity.ext.PaymentTaskEntityExt;
import com.xbongbong.saas.enums.base.PaymentTaskBaseEnum;
import com.xbongbong.saas.enums.business.PaymentTaskEnum;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PaymentTaskModel;
import com.xbongbong.saas.model.PaymentTaskSubDataModel;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: 汪腾伟
 * @date: 2020/8/3
 * @desrcption: 回款计划的操作数据库的基础实现类，简单的增删改查
 * @version:1.0
 */
@Service("paymentTaskModel")
public class PaymentTaskModelImpl implements PaymentTaskModel {

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaymentTaskDao paymentTaskDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PaymentTaskSubDataModel paymentTaskSubDataModel;
    @Resource
    private ShowFormatHelp showFormatHelp;

    @Override
    public Integer insert(PaymentTaskEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        paymentTaskDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        return null;
    }

    /**
     * 根据数据id和公司id查询具体信息
     *
     * @param formDataId 回款计划id
     * @param corpid 公司id
     * @return
     */
    @Override
    public PaymentTaskEntityExt getByKey(Long formDataId, String corpid) {
        PaymentTaskEntityExt paymentTaskEntityExt = paymentTaskDao.getByKey(formDataId, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(paymentTaskEntityExt), IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        return paymentTaskEntityExt;
    }

    /**
     * 删除回款计划
     *
     * @param dataIdList
     * @param corpid
     */
    @Override
    public Integer deleteBatch(List<Long> dataIdList, String corpid) throws XbbException {
        Integer integer = paymentTaskDao.deleteBatch(dataIdList, corpid);
        paasEsModel.deleteBatch(dataIdList, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
        paasFormSubDataModel.deleteBatchByDataId(dataIdList, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    /**
     * 批量更新回款计划
     *
     * @return
     */
    @Override
    public int batchUpdatePaymentTask(List<UpdateDataEntity> updateDataEntityList, String corpid) throws XbbException{
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataEntityList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataEntityList);
        int num = paymentTaskDao.batchUpdatePaymentTask(updateDataEntityList, corpid);
        paasEsModel.updateBatchMuchField(updateDataEntityList, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
        if (!subList.isEmpty()) {
            paymentTaskSubDataModel.updateBatch(subList, corpid);
        }
        return num;
    }

    /**
     *  根据回款计划id数组获取回款计划信息
     *
     * @param corpid 公司id
     * @param dataIdList 回款计划id列表
     * @return
     */
    @Override
    public List<PaymentTaskEntityExt> getPaymentTaskByIdList(String corpid, List<Long> dataIdList) {
        List<PaymentTaskEntityExt> paymentTaskEntityExts = paymentTaskDao.getPaymentTaskByIdList(corpid, dataIdList);
        paasFormSubDataModel.findSubEntity(corpid, paymentTaskEntityExts, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        return paymentTaskEntityExts;
    }

    /**
     * 批量新增回款计划
     *
     * @param formDataList
     * @return
     */
    @Override
    public List<PaymentTaskEntityExt> insertBatch(List<PaymentTaskEntityExt> formDataList) throws XbbException{
        for (PaymentTaskEntityExt paymentTaskEntityExt : formDataList) {
            paasFormSubDataModel.transferSubForm(paymentTaskEntityExt, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        }

        paymentTaskDao.insertBatch(formDataList);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (PaymentTaskEntityExt item : formDataList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
            item.setDataId(item.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(item, paasFormDataEntity);
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity,true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
            insertList.add(insertDTO);
        }
        paasEsModel.insertBatch(insertList);
        paasFormSubDataModel.insertBatchSubFormData(formDataList, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        return formDataList;
    }

    /**
     * 批量更新回款计划
     *
     * @param updateList
     * @param corpid
     * @return
     */
    @Override
    public Integer updateBatchForAll(List<? extends PaasFormDataEntity> updateList, String corpid) throws XbbException {
        for (PaasFormDataEntity paasFormDataEntityExt : updateList) {
            paasFormSubDataModel.transferSubForm(paasFormDataEntityExt, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        }
        Integer updateCount = paymentTaskDao.updateBatchForAll(updateList,corpid);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity entityExt : updateList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid+"_"+entityExt.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entityExt, paasFormDataEntity);
            paasFormDataEntity.setDataId(entityExt.getId());
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        return updateCount;
    }

    /**
     * 批量插入新回款计划，用于资金三期脚本迁移
     *
     * @param paymentTaskEntityExtInsertList
     * @return
     */
    @Override
    public void insertBatchIncludId(List<PaymentTaskEntityExt> paymentTaskEntityExtInsertList) throws XbbException {
        paymentTaskDao.insertBatchIncludId(paymentTaskEntityExtInsertList);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (PaymentTaskEntityExt item : paymentTaskEntityExtInsertList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
            item.setDataId(item.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(item, paasFormDataEntity);
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
            insertList.add(insertDTO);
        }
        paasEsModel.insertBatch(insertList);
    }

    /**
     * 无差别更新回款计划
     *
     * @param paymentTaskEntityExtUpdateList
     * @return
     */
    @Override
    public Integer updateAll(List<PaymentTaskEntityExt> paymentTaskEntityExtUpdateList) throws XbbException {
        Integer updateCount = paymentTaskDao.updateBatchForAll(paymentTaskEntityExtUpdateList,null);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity entityExt : paymentTaskEntityExtUpdateList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(entityExt.getCorpid()+"_"+entityExt.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entityExt, paasFormDataEntity);
            paasFormDataEntity.setDataId(entityExt.getId());
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity,true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
            insertDTOList.add(insertDTO);
        }
        //默认不抛出
        paasEsModel.updateBatch(insertDTOList, WriteRequest.RefreshPolicy.WAIT_UNTIL, false);
        return updateCount;
    }

    /**
     * 更新回款计划
     *
     * @param entity 实体
     * @return
     * @throws XbbException
     */
    @Override
    public Integer update(PaymentTaskEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        Integer success = paymentTaskDao.update(entity);
        if (Objects.equals(1, success)) {
            entity.setUpdateTime(now);
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK);
            paasEsModel.update(insertDTO);

            paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        }

        return success;
    }

    @Override
    public List findEntitys(Map<String, Object> param) {
        List<PaymentTaskEntityExt> entitys = paymentTaskDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return null;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return paymentTaskDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) {
        List<String> noEditableAttrList = PaymentTaskBaseEnum.getNoEditableList();
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            if (noEditableAttrList.contains(fieldAttrEntity.getAttr())) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            }
        }
    }

    /**
     * 对一些关联数据的处理
     *
     * @param saasAnalysisDataDTO
     * @param result
     */
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, PaymentTaskEnum.LINK_CONTRACT.getAttr(), PaymentTaskEnum.LINK_CONTRACT_HIDE.getAttr(), PaymentTaskEnum.LINK_CONTRACT.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PaymentTaskEnum.LINK_CUSTOMER.getAttr(), PaymentTaskEnum.LINK_CUSTOMER_HIDE.getAttr(), PaymentTaskEnum.LINK_CUSTOMER.getFieldType());
    }
}
